import { clipboard, nativeImage, ipcMain } from 'electron'
import { ClipboardWrite, IpcEvent, ClipboardWriteOption } from 'app/type'

export class Clipboard {
    // 写入剪切板
    static write(option: ClipboardWrite) {
        const params: ClipboardWriteOption = {}
        if (option.text) {
            params.text = option.text
        }
        if (option.html) {
            params.html = option.html
        }
        if (option.image) {
            params.image = nativeImage.createFromDataURL(option.image)
        }
        return clipboard.write(params)
    }
    // 清理剪切板
    static clear() {
        return clipboard.clear()
    }

    // 读取文本
    static readText() {
        return clipboard.readText()
    }
    // 读取格式化文本
    static readHtml() {
        return clipboard.readHTML()
    }
    // 读取图片
    static readImage() {
        return clipboard.readImage().toDataURL()
    }

    static init() {
        ipcMain.handle(IpcEvent.CLIPBOARD_WRITE, (e, option: string) => {
            return Clipboard.write(JSON.parse(option))
        })
        ipcMain.handle(IpcEvent.CLIPBOARD_CLEAR, () => {
            return Clipboard.clear()
        })
        ipcMain.handle(IpcEvent.CLIPBOARD_READ_TEXT, () => {
            return Clipboard.readText()
        })
        ipcMain.handle(IpcEvent.CLIPBOARD_READ_HTML, () => {
            return Clipboard.readHtml()
        })
        ipcMain.handle(IpcEvent.CLIPBOARD_READ_IMAGE, () => {
            return Clipboard.readImage()
        })
    }
}
